package gbase

import (
	"bytes"
	"fmt"
	"strings"
)

func mapToXmlElement(buffer *bytes.Buffer, data Map, parentTag string) error {
	buffer.WriteString(fmt.Sprintf("<%s>", parentTag))

	for key, value := range data {
		switch v := value.(type) {
		case string:
			buffer.WriteString(fmt.Sprintf("<%s>%s</%s>", key, xmlEscape(v), key))
		case int, int64, float32, float64, bool:
			buffer.WriteString(fmt.Sprintf("<%s>%v</%s>", key, v, key))
		case Map:
			err := mapToXmlElement(buffer, v, key)
			if err != nil {
				return err
			}
		case []interface{}:
			for _, item := range v {
				buffer.WriteString(fmt.Sprintf("<%s>", key))
				switch itemVal := item.(type) {
				case string:
					buffer.WriteString(xmlEscape(itemVal))
				case Map:
					err := mapToXmlElement(buffer, itemVal, key)
					if err != nil {
						return err
					}
				default:
					buffer.WriteString(fmt.Sprintf("%v", itemVal))
				}
				buffer.WriteString(fmt.Sprintf("</%s>", key))
			}
		default:
			buffer.WriteString(fmt.Sprintf("<%s>%v</%s>", key, v, key))
		}
	}

	buffer.WriteString(fmt.Sprintf("</%s>", parentTag))
	return nil
}

// 手动实现 XML 字符转义
func xmlEscape(value string) string {
	replacer := strings.NewReplacer(
		"&", "&amp;",
		"<", "&lt;",
		">", "&gt;",
		`"`, "&quot;",
		"'", "&apos;",
	)
	return replacer.Replace(value)
}
